package common.util;


import common.exceptions.CheckException;
import common.exceptions.UnloginException;
import org.springframework.context.MessageSource;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 校验工具类
 */
public class CheckUtil {
    private static MessageSource resources;

    public static void setResources(MessageSource resources) {
        CheckUtil.resources = resources;
    }

    public static void check(boolean condition, String msgKey, Object... args) {
        if (!condition) {
            fail(msgKey, args);
        }
    }

    public static void check(boolean condition) {
        if (!condition) {
            fail("field.invalid");
        }
    }

    public static void notEmpty(String str, String msgKey, Object... args) {
        if (str == null || str.isEmpty()) {
            fail(msgKey, args);
        }
    }

    public static void notObjectEmpty(Object str, String msgKey, Object... args) {
        if (str == null || str.toString().isEmpty() || str.toString().trim().equals("null")) {

            fail(msgKey, args);
        }
    }

    public static void isNumber(String str, String msgKey, Object... args) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.find()) {
            fail(msgKey, args);
        }
    }

    public static void notNull(Object obj, String msgKey, Object... args) {
        if (obj == null) {
            fail(msgKey, args);
        }
    }

    public static void notNull(Object obj) {
        if (obj == null) {
            notNull(obj, "param.is.null");
        }
    }

    private static void fail(String msgKey, Object... args) {
        System.out.println("内容:" + msgKey + "----");
//		throw new CheckException(resources.getMessage(msgKey, args, UserUtil.getLocale()));
        throw new CheckException(msgKey);
    }

    public static void notlogin(String msgKey) {
        throw new UnloginException(msgKey);
    }
}
